package com.kw.drug.controller;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.kw.drug.common.ResultMapUtil;
import com.kw.drug.entity.User;
import com.kw.drug.mapper.UserMapper;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.Map;

@Controller
public class UserController {
    @Autowired
    UserMapper userMapper;

    /**
     * 访问登陆页面
     */
    @RequestMapping("/login")
    public String toLogin() {
        return "login";
    }

    /**
     * 判断登录是否成功
     */

    @PostMapping("/toLogin")
    @ResponseBody
    public Map judge(@RequestParam String username, @RequestParam String password, HttpSession session) {

        //获取当前的用户
        Subject subject = SecurityUtils.getSubject();
        //封装用户的登录数据
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        try {
            subject.login(token); //执行登录方法 如果没有异常就说明ok了


            return ResultMapUtil.getHashMapLogin("登录成功", "1");
        } catch (UnknownAccountException e) {


            return ResultMapUtil.getHashMapLogin("用户名或者密码错", "2");
        } catch (IncorrectCredentialsException e) {

            return ResultMapUtil.getHashMapLogin("用户名或者密码错误", "2");
        }
    }

    /**
     * 后台首页
     */
    @GetMapping("/index")
    public String index() {
        return "index";
    }

    /**
     * 用户退出
     */
    @RequestMapping("logout")
    public String logout(HttpSession session) {
        session.invalidate();
        return "login";
    }
     /**
     * 调到用户修改页面
     */
    @RequestMapping("toxiugaimima")
    public String toXiuGaiMiMa() {
        return "xiugaimima";
    }
    /**
     * 用户修改密码
     */
    @RequestMapping("xiugaimima")
    public String xiuGaiMiMa(@RequestParam String username,
                             @RequestParam String password, HttpSession session) {
        User user =(User) session.getAttribute("user");
        if (!user.getUsername().equals(username)){
            System.out.println("1");
        }if (!StringUtils.isEmpty(password) ){
            System.out.println("2");
        }
        //去数据库修改密码
        userMapper.xiugaimima(username,password);
        return "login";
    }



}
